const db = require('../utils/mysql');
const moment = require('moment');
const md5 = require('md5');

const jwt = require("jwt-simple");


/*
CREATE TABLE users(
    u_id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
    u_name VARCHAR(20) NOT NULL UNIQUE,
    u_pwd  VARCHAR(50) NOT NULL,
    u_sex  VARCHAR(1)  DEFAULT '女',
    u_status VARCHAR(1) DEFAULT 1,
    u_createtime DATETIME
);
INSERT INTO users (`u_name`,`u_pwd`,`u_sex`,`u_status`,`u_createtime`) VALUES(?,?,?,?)

127.0.0.1:3333/account/register?name=test&pwd=123&sex=女&status=1
* */

/**
 * 账户管理类
 */
class AccountController {
    // register = async ()=>{}
    /**
     * 注册账户
     * @param request
     * @param response
     * @param next
     * @returns {Promise<void>}
     */
    async register(request, response, next) {
        // console.log(request.method)
        if (request.method == "GET") {
            // console.log('--------------------')
            response.render('register',{msg:'我是小三...........'})
            // response.send('注册页面')
        } else {

            let insertSql = 'INSERT INTO users (`u_name`,`u_pwd`,`u_sex`,`u_status`,`u_createtime`) VALUES(?,?,?,?,?);';
            let parms = [
                request.body.name,
                md5(request.body.pwd + require("../config").key),
                request.body.sex === undefined ? "男" : request.body.sex,
                request.body.status == null ? 1 : request.body.status,
                moment().format('YYYY-MM-DD HH:mm:ss')
            ]
            // console.log(parms);

            try {
                let result = await db.exec(insertSql, parms);
                if (result && result.affectedRows >= 1) {
                    response.json({
                        code: 200,
                        msg: "注册成功",
                    });
                } else {
                    response.json({
                        code: 201,
                        msg: "注册失败",
                        result
                    })
                }
            } catch (error) {
                response.json({
                    code: -200,
                    msg: "服务器异常",
                    error
                })
            }
            // response.send('POST请求。。。。。。。。。')
        }

    }

    /**
     * 账户登录
     * @param request
     * @param response
     * @param next
     * @returns {Promise<void>}
     */
    async login(request, response, next) {
        let loginSql = "SELECT `u_id`,`u_name`,`u_sex`,`u_status`,`u_createtime` " +
            "FROM users WHERE  u_name=? AND u_pwd=? AND u_status=1;";
        let params = [
            request.body.name,
            md5(request.body.pwd + require("../config").key)
        ]

        try {
            let result = await db.exec(loginSql, params);
            if (result && result.length >= 1) {
                response.json({
                    code: 200,
                    msg: "登陆成功",
                    data: result[0],
                    token: createToken(result[0])
                });
            } else {
                response.json({
                    code: -200,
                    msg: "登陆失败",
                });
            }
        } catch (error) {
            response.json({
                code: -200,
                msg: "服务器异常",
                error
            })
        }

        // response.send('登录页面')
        function createToken(data) {
            return jwt.encode({
                exp: Date.now() + (1000 * 60 * 60 * 24),
                info: data
            }, require("../config").tokenKey);
        }
    }
}


module.exports = new AccountController();